layui.define(['api', 'jquery', 'func'], function (exports) {
    const {jquery: $, api, func} = layui;
    // if (!window.xmSelect) {
    //     //动态载入依赖
    //     var script = document.createElement('script');
    //     script.type = 'text/javascript';
    //     script.src = '/biz/js/xm-select.js';
    //     $("body").append(script);
    //     script.onload = script.onreadystatechange = function () {
    //         if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
    //             handler();
    //             script.onload = script.onreadystatechange = null;
    //         }
    //     };
    // } else {
    handler();

    // }

    function handler() {
        exports('xm_select', {
            render: function (config) {
                var {name, url, param, value, extra} = config;
                var object = null;
                if (!extra) {
                    extra = {};
                } else {
                    extra = eval("(" + extra + ")");
                }

                api(url, {}, 'POST').then(function (res) {
                    object = window.xmSelect.render(Object.assign({
                        el: config.elem,
                        theme: {
                            color: 'var(--biz-theme-color)',
                        },
                        name: name,
                        data: res.data,
                        autoRow: true,
                        toolbar: {show: true},
                        filterable: true,
                        remoteSearch: true,
                        remoteMethod: function (val, cb, show) {
                            var data = {};
                            data[param] = val;
                            //这里如果val为空, 则不触发搜索
                            api(url, data, 'POST').then(function (res) {
                                cb(res.data);
                            }).catch(function () {
                                cb([]);
                            });
                        },
                    }, extra));

                    if (!$.isArray(value)) {
                        value = value.toString().split(',');
                    }
                    object.setValue(value);
                })
            }
        });
    }

});